<?php
/**
 * Class Xu ly thong thong tin loai danh muc
 */
class Listxml_ListTypeController extends  Zend_Controller_Action {
	public function auth(){
        $url = Efy_Init_Config::_getCurrentHttpAndHost();
        if (($_SESSION['STAFF_PERMISSTION'] != 'ADMIN_SYSTEM') && ($_SESSION['STAFF_PERMISSTION'] != 'ADMIN_OWNER')){
            $url = $url .'public/error/index/';
            $this->_redirect($url);
        }
    }
	public function init(){
		$this->auth();
		Zend_Loader::loadClass('Zend_Json');
		Zend_Loader::loadClass('Listxml_modListType');
		//Load cau hinh thu muc trong file config.ini
        $tempDirApp = Zend_Registry::get('conDirApp');
		$this->_dirApp = $tempDirApp->toArray();
		$this->view->dirApp = $tempDirApp->toArray();
		if (!$this->_request->isXmlHttpRequest()){
			//Cau hinh cho Zend_layout
			Zend_Layout::startMvc(array(
				    'layoutPath' => $this->_dirApp['layout'],
				    'layout' => 'index'
				    ));
			//Load ca thanh phan cau vao trang layout (index.phtml)
			$response = $this->getResponse();
			//Load cau hinh thu muc trong file config.ini de lay ca hang so dung chung
	        $tempConstPublic = Zend_Registry::get('ConstPublic');
			$this->_ConstPublic = $tempConstPublic->toArray();
			//Lay so dong treng man hinh danh sach
			$this->view->NumberRowOnPage 	= $this->_ConstPublic['NumberRowOnPage'];		
			
			//Ky tu dac biet phan tach giua cac phan tu
			$this->view->delimitor 			= $this->_ConstPublic['delimitor'];
			
			//Lay duong dan thu muc goc (path directory root)
			$this->view->baseUrl = $this->_request->getBaseUrl() . "/public/";	
					
			// Goi lop public		
			$objPublicLibrary = new Efy_Library();
			
			// Load tat ca cac file Js va Css
			$this->view->LoadAllFileJsCss = $objPublicLibrary->_getAllFileJavaScriptCss('public/efy-js/ListType','','','','js') . $objPublicLibrary->_getAllFileJavaScriptCss('public/efy-js/ListType','','','','css')
			.Efy_Publib_Library::_getAllFileJavaScriptCss('','efy-js','ListType/publicsystem.js',',','js')	
			;
			/* Ket thuc 		*/		
			//Lay cac hang so su dung trong JS public		
			$objConfig = new Efy_Init_Config();
			$this->view->JSPublicConst = $objConfig->_setJavaScriptPublicVariable();					
			//Dinh nghia current modul code
			$this->view->currentModulCode = "ADMIN";
			$this->view->currentModulCodeForLeft = "listtype";		
			//Hien thi file template
			$response->insert('header', $this->view->renderLayout('header.phtml','./application/views/scripts/'));    	//Hien thi header 
			$response->insert('menu', $this->view->renderLayout('menu.phtml','./application/views/scripts/'));    		//Hien thi header 		    
	        $response->insert('footer', $this->view->renderLayout('footer.phtml','./application/views/scripts/'));  	 //Hien thi footer
	        $sGetValueInCookie = Efy_Library::_getCookie("showHideMenu");
			if ($sGetValueInCookie == "" || is_null($sGetValueInCookie) || !isset($sGetValueInCookie)){
				Efy_Library::_createCookie("showHideMenu",1);
				$this->view->hideDisplayMeneLeft = 1;
			}else{//Da ton tai Cookie
				if ($sGetValueInCookie != 0){
					$this->view->hideDisplayMeneLeft = 1;
				}else{
					$this->view->hideDisplayMeneLeft = "";
				}
			}
		}else{
			$result = array();

			$result = Efy_Publib_Library::_getAllFileJavaScriptCssArray('','efy-js/ListType','dhtmlwindow.js,ListType.js,publicsystem.js,',',','js',$result);
			$result = Efy_Publib_Library::_getAllFileJavaScriptCssArray('','efy-js','ListType/dhtmlwindow.css',',','css',$result);
			$this->view->arrJsCss = Zend_Json::encode($result);
		}
	}	
	
	/**
	 * Creater : HUNGVM
	 * Date :
	 * Idea : Tao phuong thuc hien thi danh sach loai danh muc
	 *
	 */
	// Xu ly thong tin de day ra file index.phtml
	public function indexAction(){
		//Tao cac doi tuong
		$objFunction = New Efy_Function_RecordFunctions();
		$this->view->bodyTitle = 'DANH SÁCH CÁC LOẠI DANH MỤC';

		$filexml = 'http://'.$_SERVER['HTTP_HOST'].$this->_request->getBaseUrl() .'/xml/list/' . 'man_hinh_danh_sach.xml';
		//Render view
		$this->view->filexml = $filexml;
		$this->view->arrListItem = $objFunction->getAllObjectbyListCode('','DM_SO_HS_TREN_TRANG');
		$this->view->iCurrentPage = 1;
		$this->view->iNumberRecordPerPage = 15;
		
	}
	public function recordAction(){
		//Tao doi tuong
		$objListType = new Listxml_modListType();
		//Lay tieu chi tim kiem
		$sListTypeName =$this->_request->getParam('txtSearch','');
		$iStatus = '';
		$sOwnerCode = $_SESSION['OWNER_CODE'];
		$hdn_current_page = $this->_request->getParam('hdn_current_page');
		$hdn_record_number_page = $this->_request->getParam('hdn_record_number_page');
		//Mảng lưu danh sách
		$arrResult = $objListType->getAllListType($iStatus,$sListTypeName,$sOwnerCode,$hdn_current_page,$hdn_record_number_page);
		//Đẩy dữ liệu vào Json
		echo Zend_Json::encode($arrResult);
		$this->_helper->getHelper('viewRenderer')->setNoRender();
	}
	
	/**
	 * @see : Thuc hien Them moi LOAI DANH Muc
	 *
	 */
	public function addAction(){
		if (!$this->_request->isXmlHttpRequest()){
			return $this->_helper->redirector('index');
		}
		// Tieu de cua Form cap  nhat
		$this->view->bodyTitle = 'CẬP NHẬT MỘT LOẠI DANH MỤC';
		//Gan gia tri mac dinh cho cac Input
		$this->view->parError = '';
		
		// goi load div 
		$this->view->divDialog = $this->showDialog();
		
		// Thuc hien lay du lieu tu form 		
		if($this->_request->isPost()){	
			// Lay toan bo tham so truyen tu form			
			$arrInput = $this->_request->getParams();				
						
			// Tao doi tuong Zend_Filter
			$filter = new Zend_Filter();
			
			// Thuc hien tao mot mang de day vao view
			$arrInput['C_CODE'] = $this->_request->getParam('C_CODE');
			$arrInput['C_NAME'] = $this->_request->getParam('C_NAME');
			$arrInput['C_IMPORT_STATUS'] = $this->_request->getParam('C_IMPORT_STATUS');
			$arrInput['C_AUTO_GENERATE_OBJECT_STATUS'] = $this->_request->getParam('C_AUTO_GENERATE_OBJECT_STATUS');
			
			$arrInput['CHK_IMPORT_STATUS'] = $this->_request->getParam('CHK_IMPORT_STATUS');
			$arrInput['CHK_AUTO_GENERATE_OBJECT_CODE'] = $this->_request->getParam('CHK_AUTO_GENERATE_OBJECT_CODE');
			$arrInput['TXT_AUTO_GENERATE_OBJECT_CODE'] = $this->_request->getParam('TXT_AUTO_GENERATE_OBJECT_CODE');
			$arrInput['C_XML_FILE_NAME'] = $this->_request->getParam('C_XML_FILE_NAME');
			$this->view->arrInput = $arrInput;
			// Lay so thu tu lon nhat gan vao 
			$this->view->arrInput['C_ORDER'] = $filter->filter($this->_request->getParam('hdn_order'));
		}
				
	}		
	public function saveAction(){
		// Tao doi tuong modeListType
		$objListType= new Listxml_modListType();
		$objEfyLibrary = new Efy_Library();
		//Lay cac tham so cua form
		$sListTypeCode				= trim($objEfyLibrary->_restoreXmlBadChar($this->_request->getParam('C_CODE')));				
		$sListTypeName 				= trim($objEfyLibrary->_restoreXmlBadChar($this->_request->getParam('C_NAME')));
		$sChkImportStatus 			= trim($objEfyLibrary->_restoreXmlBadChar($this->_request->getParam('CHK_IMPORT_STATUS')));
		$sChkAutoGenerateStatus 	= trim($objEfyLibrary->_restoreXmlBadChar($this->_request->getParam('CHK_AUTO_GENERATE_OBJECT_CODE')));
		$sTxtAutoGenerateObjectCode = trim($objEfyLibrary->_restoreXmlBadChar($this->_request->getParam('TXT_AUTO_GENERATE_OBJECT_CODE')));		
		if (!$sChkAutoGenerateStatus){
			$sTxtAutoGenerateObjectCode = "";
		}
		$iListTypeOrder 			= trim($this->_request->getParam('C_ORDER'));
			
		// Ten file up load
		// Lay ten file khi chon tu server
		if(isset($_FILES['C_XML_FILE_NAME']['name'])){
			$sListTypeXml = $_FILES['C_XML_FILE_NAME']['name'];
		}else{
			$sListTypeXml = $this->_request->getParam('txt_xml_file_name');
		}
		
		//Id loai danh muc
		//PK_LISTTYPE
		$iListTypeId =(int)$this->_request->getParam('hdn_listtype_id');
		
		//Trang thai cua doi tuong danh muc (HOAT_DONG : hoat dong; NGUNG_HOAT_DONG ; Ngung hoat dong)
		$sStatus = 'NGUNG_HOAT_DONG';
		if ($this->_request->getParam('C_STATUS')){
			$sStatus = 'HOAT_DONG';
		}
		
		// Lay don vi su dung
		$arrListTypeOwnerCodeList = $this->_request->getParam('chk_onwer_code_list');
		$sListTypeOwnerCodeList = '';
		for ($i = 0; $i < sizeof($arrListTypeOwnerCodeList) - 1; $i++)
			$sListTypeOwnerCodeList .= $arrListTypeOwnerCodeList[$i] . ',';
		$sListTypeOwnerCodeList .= $arrListTypeOwnerCodeList[sizeof($arrListTypeOwnerCodeList) - 1];
		$isSaveAndAddNew = 	$this->_request->getParam('C_SAVE_AND_ADD_NEW');						
		// xu ly viec copy file len o cung
		if($_FILES['C_XML_FILE_NAME']['name'] != ""){
			move_uploaded_file($_FILES['C_XML_FILE_NAME']['tmp_name'], "../xml/list/" . $_FILES['C_XML_FILE_NAME']['name']);
			$sListTypeXml = $_FILES['C_XML_FILE_NAME']['name'];					
		}

		// Thuc hien cap nhat vao csdl								
		$arrResult = $objListType->updateListType($iListTypeId,$sListTypeCode,$sListTypeName,$iListTypeOrder,$sListTypeXml,$sStatus,$sListTypeOwnerCodeList,$sChkImportStatus,$sChkAutoGenerateStatus, $sTxtAutoGenerateObjectCode);
		$this->_helper->getHelper('viewRenderer')->setNoRender();
	}
	/**
	 * @see : Thuc hien viec sua Mot hoac Nhieu Loai Danh muc
	 */
	public function editAction(){
		if (!$this->_request->isXmlHttpRequest()){
			return $this->_helper->redirector('index');
		}
		// Tieu de cua Form cap  nhat
		$this->view->bodyTitle = 'CẬP NHẬT MỘT LOẠI DANH MỤC';
		
		//Gan gia tri mac dinh cho cac Input Error
		$this->view->parError = '';	
		
		// Tao doi tuong cho lopr Filter
		$filter = new Zend_Filter();
		
		// goi load div 
		$this->view->divDialog = $this->showDialog();
		
		//  Lay id cua ban ghi
		$iListTypeId = (int)$this->_request->getParam('PK_LISTTYPE');
		$this->view->iListTypeId = $iListTypeId;
		// Tao doi tuong 
		$objListType = new  Listxml_modListType();
		$listTypeCode = $objListType->GetListTypeCode($iListTypeId);
		// Tao doi tuong Efy	
	   	$objEfyLibrary = new Efy_Library();
	   		
		// Lay thong tin trong csdl
		$arrResult = $objListType->getSingleListType($iListTypeId);
		//var_dump($arrResult);exit;	
		//	xu ly du lieu de dua vao mang	
		$arrTempResult = array(
			'PK_LISTTYPE'=> $arrResult[0]['PK_LISTTYPE'],
			'C_CODE'=> trim($objEfyLibrary->_replaceBadChar($arrResult[0]['C_CODE'])),
			'C_NAME' => trim($objEfyLibrary->_replaceBadChar($arrResult[0]['C_NAME'])),
			'C_ORDER' => $arrResult[0]['C_ORDER'],
			'C_XML_FILE_NAME'=>$arrResult[0]['C_XML_FILE_NAME'],
			'C_STATUS' => $arrResult[0]['C_STATUS'],
			'C_OWNER_CODE_LIST' => $arrResult[0]['C_OWNER_CODE_LIST'],
			'C_IMPORT_STATUS'=>$arrResult[0]['C_IMPORT_STATUS'],
			'C_AUTO_GENERATE_OBJECT_STATUS' => $arrResult[0]['C_AUTO_GENERATE_OBJECT_STATUS'],
			'C_AUTO_GENERATE_OBJECT_CODE' => $arrResult[0]['C_AUTO_GENERATE_OBJECT_CODE']
		);				
		// Thuc hien bind du lieu vao view
	   $this->view->arrInput = $arrTempResult;
	   
	   // Xu ly nut Tinh trang
	   if($arrTempResult['C_STATUS']==1){
	   		$this->view->bStatus = true;	   	
	   }else {
			$this->view->bStatus = false;	   	
	   }
	}
	/**
	 * @see : Thuc hien viec xoa Mot hoac Nhieu Loai Danh muc
	 */
	public function deleteAction(){
		//Request hidden luu id da duoc chon
		$sListTypeIdList = $this->_request->getParam('hdn_object_id_list');

		// Tao doi tuong ListType
		$objListType = new  Listxml_modListType();
		
		// thuc hien cau lenh xoa		
		$arrResult = $objListType->deleteListType($sListTypeIdList);
		// Kiem tra 
		if($arrResult != null || $arrResult != '' ){											
			echo "<script type='text/javascript'>";
			echo "alert('$arrResult');";	
			echo "</script>";
		}else {
			//Tra ve trang index
			$arrListTypeCode = $objListType->GetListTypeCodeFromIdList($sListTypeIdList);
			foreach ($arrListTypeCode as $value){
				if (file_exists('xml/list/output/'.$value.'.xml'))
					unlink('xml/list/output/'.$value.'.xml');
			}
			echo 'OK';
			//$this->_redirect('listxml/listtype/index/');
		}
		die();
	}	
/**
 * @see : Thuc hien lay file doc tat ca cac file xml tu o cung cua server
 * @creator: Thainv
 * @createdate: 
 * 
 * 
 * 	*/
	
	private function showDialog(){
		
		$dir = "./xml/list/";				
		$objConfig = new Efy_Init_Config();
		$sResHtml = '';
		$sResHtml = $sResHtml. "<div style='overflow:auto;height:95%; width:98%; padding: 6px 2px 2px 2px;'>";	
		
		if (is_dir($dir)) {
		    if ($dh = opendir($dir)) {
		        while (($file = readdir($dh)) !== false) {
		        	// kt la file xml thi hien thi		        	
		        	$filetype = substr($file,strlen($file)-4,4);			        	
		        	$filetype = strtolower($filetype);
		        	if($filetype == ".xml"){		            	
		            	$sResHtml = $sResHtml . "<p  class='normal_label' style='width:95%'  align='left' >";		            	
		            	$sResHtml = $sResHtml . " 	<img src ='".$objConfig->_setImageUrlPath() ."file_icon.gif' width='12' />" ;	
						$sResHtml = $sResHtml . "		<a href='#' onClick =\"getFileNameFromDiv('".$file. "')\">" . $file . "</a>";
		            	$sResHtml = $sResHtml . "</p>";
		        	}	
		        }
		        closedir($dh);
		    }
		}
		$sResHtml = $sResHtml.'</div>';	
		
		return  $sResHtml;
	}
	public function xmlAction(){
		Zend_Loader::loadClass('Listxml_modList');
		$objList = new Listxml_modList();
		$arrTempList = $objList->createXMLDb('');
		$sOwnerCode	= $_SESSION['OWNER_CODE'];
		// duong dan 		
		$sFilePath = 'xml/list/output/';
		if(!file_exists($sFilePath)){
			mkdir($sFilePath, 0777);
		}
		// Thuc hien Tao file xml
		$this->createXML($sFilePath,$arrTempList);
		echo 'Xuất thành công!';
		die();
	}	
	/**
	 * @see : Ham thuc hien tao file xml 
	 * @author: Trinh Thanh Phuong
	 * @date: 13/10/2011
	 * */
	private function createXML($pFilePath,$arrList){
		$strXmlItem = '';
		$listTypeCode = $arrList[0]['LISTTYPE_CODE'];
		$strXml = '<?xml version="1.0" encoding="UTF-8"?><root><data_list>';
		$count = sizeof($arrList); 	
		for ($i = 0; $i < $count; $i++){
			if ($listTypeCode != $arrList[$i]['LISTTYPE_CODE']){
				$strXml .= '</data_list></root>';
				Efy_Library::_writeFile($pFilePath.$listTypeCode.'.xml',$strXml);
				$listTypeCode = $arrList[$i]['LISTTYPE_CODE'];
				$strXml = '<?xml version="1.0" encoding="UTF-8"?><root><data_list>';
			}
			$strXmlItem = '<item><c_status>'.$arrList[$i]['C_STATUS'].'</c_status><c_code>'.$arrList[$i]['C_CODE'].'</c_code><c_name>'.$arrList[$i]['C_NAME'].'</c_name><c_owner_code>'.$arrList[$i]['C_OWNERCODE'].'</c_owner_code>';
			if ($arrList[$i]['C_XML_DATA'] != ''){
				$xmlData = '<?xml version="1.0" encoding="UTF-8"?>'.$arrList[$i]['C_XML_DATA'];
				$objXmlData = new Zend_Config_Xml($xmlData,'data_list');
				$arrXmlData = $objXmlData->toArray();
				$arrKey = array_keys($arrXmlData); 
				foreach ($arrKey As $value){
					$strXmlItem .= '<'.$value.'>'.$arrXmlData[$value].'</'.$value.'>';	
				}
			}
			$strXmlItem .= '</item>';
			$strXml .= $strXmlItem;
		}
		$strXml .= '</data_list></root>';
		Efy_Library::_writeFile($pFilePath.$listTypeCode.'.xml',$strXml);		
	}	
}
?>